<template>
  <div style="display: flex; justify-content: center;">
    <div
      :id="id"
      :class="className"
      :style="{ height: height + 'px', width: width }"
    />
    <div class="control" style="width: 30%;">
      <div class="legend mt16">
        <div
          class="card flex-h-sb flex-v-center"
          v-for="(item, i) in series_obj1"
          :key="i"
        >
          <div class="left tof flex-v-center">
            <el-checkbox
              style="margin: 2px 5px 0 14px;"
              class="flex-v-center"
              v-model="item.status"
              @change="legendHandle(item.key)"
            ></el-checkbox>
            <div class="legend-name tof">
              <p>{{ item.name }}<span v-if="item.investStatus">（{{typeList[item.investStatus-1]}}）</span></p>
              <div class="line1" :style="`border: 1px solid ${item.itemStyle.color};`"></div>
            </div>
          </div>
        </div>
        <div class="fillcard"></div>
      </div>
      <div  class="showAll showAll2 flex-hc-sb">
        <el-checkbox v-model="investIntoSubInvest_showAll" @change="investIntoSubInvestChange('investIntoSubInvest_showAll')">显示全部</el-checkbox>
        <el-checkbox v-model="investIntoSubInvest_showSome" @change="investIntoSubInvestChange('investIntoSubInvest_showSome')">显示"进行中的子投资"</el-checkbox>
      </div>
    </div>
  </div>
</template>

<script>
import * as echarts from 'echarts'
import mixin from './mixins'
import { upFixed, downFixed } from '@/utils'
import { color_list } from './const'
import { parseTime } from '@/utils'
export default {
  mixins: [mixin],
  props: {
    chartData: {
      type: Array | Object,
    },
    className: {
      type: String,
      default: 'chart',
    },
    id: {
      type: String,
      default: 'chart',
    },
    width: {
      type: String,
      default: '100%',
    },
    height: {
      type: Number,
      default: 200,
    },
  },
  data() {
    return {
      chart: null,
      xDate: [], // y轴
      series_obj1: [],
      fitNetWorth_obj: {}, // 拟合
      netWorth_obj: {}, // 净值
      contrastIndex_obj: {}, // 指数
      legendStatus: {},
      chart_option: {},
      lineEcahrts_showAll: false,
      typeList: ['未开始', '进行中', '已结束'],
      investIntoSubInvest_showAll: false,
      investIntoSubInvest_showSome: false
    }
  },
  beforeDestroy() {
    if (!this.chart) {
      return
    }
    this.chart.dispose()
    this.chart = null
  },
  computed: {
    // nameLegendsCom() {
    //   return this.series_obj1
    // },
  },
  methods: {
    initChart(obj1) {
      const base_netWorth = []
      const chartDataOption = []
      this.xDate = []
      obj1.forEach((items, index) => {
        this.xDate.push(parseTime(items.date))
        items.item.map((el, i) => {
          // if (index == 0) base_netWorth[i] = el.netWorth - 1
          if (index == 0) base_netWorth[i] = 0
          el.pnl = el.pnl ? Number(el.pnl) : 0
          if (!chartDataOption[el.key]) chartDataOption[el.key] = []
          if (el.netWorth != null) {
            const val = (el.netWorth - base_netWorth[i]).toFixed(4)
            chartDataOption[el.key].push(val)
          } else {
            chartDataOption[el.key].push(null)
          }
        })
      })
      this.chart = echarts.init(document.getElementById(this.id))
      this.series_obj1 = []
      if (Object.keys(chartDataOption).length) {
        Object.keys(chartDataOption).forEach((key, i) => {
          const item = chartDataOption[key]
          const isIndex = obj1[0].item.find(item => item.key==key).isIndex
          if(!(i==0||isIndex)) this.legendStatus[key] = false  // 初始化勾选状态
          this.series_obj1.push({
            name: key,
            key: key,
            type: 'line',
            symbolSize: 2,
            investStatus: obj1[0].item.find(item => item.key==key).investStatus,
            symbol: 'emptyCircle',
            status: i==0||isIndex,
            isIndex: isIndex,
            showSymbol: false,
            lineStyle: {
              width: 1.6,
            },
            itemStyle: {
              color: color_list[i],
            },
            data: item,
            connectNulls: true,
          })
        })
      }
      this.chart_option = {
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            textStyle: {
              color: '#fff',
            },
          },
          formatter(params) {
            let str = ''
            str += `<div style="padding-bottom: 2px;">${params[0].name}</div>`
            for (let i = 0; i < params.length; i += 1) {
              if (params[i].data != null) {
                str += `<div style="display: flex;align-items: center;">
                      ${params[i].marker}
                      <span style="flex:1;">${params[i].seriesName}</span>
                      <span style="margin-left: 10px;font-weight: bold;"> ${params[i].data}</span>
                      </div>`
              } else {
                str += `<div style="display: flex;align-items: center;">
                      ${params[i].marker}
                      <span style="flex:1;">${params[i].seriesName}</span>
                      <span style="margin-left: 10px;font-weight: bold;"> --</span>
                      </div>`
              }
            }
            return str
          },
        },
        grid: {
          top: '15%',
          left: '7%',
          right: '5%',
          bottom: '20%',
          borderWidth: 0,
          textStyle: {
            color: '#fff',
          },
        },
        legend: {
          show: false,
          right: '20',
          top: '2%',
          type: 'scroll',
          textStyle: {
            color: '#90979c',
          },
          selected: this.legendStatus
        },
        calculable: true,
        xAxis: [
          {
            type: 'category',
            boundaryGap: false, // 折线从x轴起始开始走
            splitNumber: 8,
            axisLine: {
              lineStyle: {
                color: '#90979c',
              },
            },
            splitLine: {
              show: false,
            },
            axisTick: {
              show: true,
              alignWithLabel: true,
              interval: 'auto',
            },
            splitArea: {
              show: false,
            },
            axisLabel: {
              interval: 'auto',
            },
            data: this.xDate,
          },
        ],
        yAxis: [
          {
            type: 'value',
            min: (value) => {
              const num = value.min - (value.max - value.min) / 5
              return downFixed(num, 1)
            },
            max: (value) => {
              const num = value.max + (value.max - value.min) / 5
              return upFixed(num, 1)
            },
            splitNumber: 5,
            splitLine: {
              show: true,
              lineStyle: {
                type: 'dashed',
              },
            },
            axisLine: {
              show: true,
              lineStyle: {
                color: '#90979c',
              },
            },
            axisTick: {
              show: true,
              alignWithLabel: true,
            },
            axisLabel: {
              interval: 0,
              formatter: (value) => {
                return value.toFixed(4)
              },
            },
            splitArea: {
              show: false,
            },
          },
        ],

        dataZoom: [
          {
            show: false,
            type: 'slider',
            start: 0,
            end: 100,
            realtime: true,
            height: '0%',
            bottom: '18%',
          },
          {
            brushSelect: false,
            realtime: true, // 实时更新系列的视图
            height: '7%',
            bottom: '5%',
          },
        ],
        series: this.series_obj1,
      }
      this.chart.setOption(this.chart_option)

      // this.chart.on('datazoom', () => {
      //   const op = this.chart.getOption()
      //   // const baseline_i = this.chart.getModel().option.dataZoom[0].startValue
      //   const list = this.xReturnZero(this.fitNetWorth_obj)

      //   Object.keys(list).forEach((key, index) => {
      //     const item = list[key]
      //     const i = op.series.findIndex((os) => os.name == key)
      //     console.log(11, i, item)
      //     if (i != -1) {
      //       op.series[i].data = item
      //     }
      //   })
      //   this.chart.setOption(op)
      // })
    },
    investIntoSubInvestChange(val) {
      if((!this.investIntoSubInvest_showAll) && (!this.investIntoSubInvest_showSome)) {
        this.lineEcahrts_showAll = false
        this.series_obj1.map((item, i) => {
          if(i==0||item.isIndex) {
            this.legendStatus[item.key] = true
            item.status = true
          }else {
            this.legendStatus[item.key] = false
            item.status = false
          }
        })
      this.chart.setOption(this.chart_option)
      }else if(val == 'investIntoSubInvest_showAll') {
        this.investIntoSubInvest_showSome = false
        this.lineEcahrtsShowAllHandle()
      }else if(val == 'investIntoSubInvest_showSome') {
        this.investIntoSubInvest_showAll = false
        this.lineEcahrts_showAll = false
        this.series_obj1.map(item => {
          if(item.investStatus==2) {
            this.legendStatus[item.key] = true
            item.status = true
          }else {
            this.legendStatus[item.key] = false
            item.status = false
          }
        })
        this.chart.setOption(this.chart_option)
      }
    },
    xReturnZero() {
      const baseline_i = this.chart.getModel().option.dataZoom[0].startValue
      const res = []
      const base_netWorth = []
      Object.keys(this.fitNetWorth_obj).forEach((key, index) => {
        const items = this.fitNetWorth_obj[key]
        res[key] = []
        items.forEach((item, i) => {
          if (i == 0) base_netWorth[index] = items[baseline_i] - 1
          if (item != null) {
            const val = (item - base_netWorth[index]).toFixed(4)
            res[key].push(val)
          } else {
            res[key].push(null)
          }
        })
      })
      return res
    },
    legendHandle(key) {
      this.chart.dispatchAction({
        type: 'legendToggleSelect',
        name: key
      })
    },
    lineEcahrtsShowAllHandle() {
      this.lineEcahrts_showAll = !this.lineEcahrts_showAll
      this.series_obj1.map(item => { 
        this.legendStatus[item.key] = this.lineEcahrts_showAll
        item.status = this.lineEcahrts_showAll
      })
      this.chart.setOption(this.chart_option)
    },
  },
}
</script>
<style lang="scss" scoped>
.control {
  position: relative;
  width: 432px;
  display: flex;
  flex-direction: column;
  margin-left: 24px;
  height: 380px;
  .beyondIncome {
    .shortline {
      width: 20px;
      border: 1px solid #d9d9d9;
    }
  }
  .showReal {
    padding: 0 13px 0 14px;
  }
  .legend {
    // margin-top: 15px;
    min-width: 432px;
    height: 100%;
    overflow: auto;
    background: #fafafa;
    border-radius: 8px;
    .card {
      height: 48px;
      cursor: pointer;
      padding: 0 13px 0 14px;
      box-shadow: inset 0px -1px 0px 0px #f0f0f0;
      &:hover {
        background: #ffffff;
        box-shadow: inset 0px -1px 0px 0px #f0f0f0;
      }
      .left {
        width: 240px;
      }
      .right {
        width: 150px;
        font-size: 12px;
        color: #8c8c8c;
        p {
          text-align: right;
        }
      }
      .legend-name {
        .line {
          width: 28px;
          margin-left: 6px;
        }
      }
    }
  }
  .legend-name {
    .line {
      width: 28px;
      margin-left: 6px;
    }
    .line1 {width: 28px;}
  }
  .mt16 {
    margin-top: 16px;
  }
  .icon-zhihuan {
    color: #1890ff;
    cursor: pointer;
  }
  .fillcard {
    height: 48px;
  }
  .showAll {
    width: 99.8%;
    line-height: 48px;
    background: rgba(166, 166, 166, 0.4);
    border-radius: 0px 0px 8px 8px;
    position: absolute;
    bottom: 0;
    text-align: center;
    margin: 0 auto;
  }
  .showAll2 {
    height: 48px;
    padding: 0 60px;
  }
}
</style>
